package bhwz.seac3.util;

import java.io.*;

import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.util.XMLResourceDescriptor;
import org.w3c.dom.svg.SVGDocument;

public class SVGManager {

	public byte[] encodeImage(String path) {
		if (path == null)
			return null;
		return fileToByte(path);
	}

	public SVGDocument decodeImage(byte[] image) throws ClassNotFoundException,
			IOException {
		if (image == null)
			return null;
		File f=byteToFile(image);
		return readSVG(f.getAbsolutePath());
	}
	
	private SVGDocument readSVG(String path) throws IOException {
		if(path==null)
			return null;
		File file = new File(path);
		String parser = XMLResourceDescriptor.getXMLParserClassName();
		SAXSVGDocumentFactory f = new SAXSVGDocumentFactory(parser);
		return f.createSVGDocument(file.toURI().toString());
	}

	private byte[] fileToByte(String filename) {
		byte[] b = null;
		File file = new File(filename);
		b = new byte[(int) file.length()];
		try (BufferedInputStream is = new BufferedInputStream(
				new FileInputStream(file))) {
			is.read(b);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return b;
	}

	public File byteToFile(byte[] fileContent) {
		try {
			File file = File.createTempFile("teamicon", ".svg");
			try (BufferedOutputStream os = new BufferedOutputStream(
					new FileOutputStream(file))) {
				os.write(fileContent);
			}
			return file;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}

	}

}
